package CPM;

import java.io.BufferedReader;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.HashMap;

public class entityTrigrams {

	public static void main(String args[]) throws Exception {
		try {

			Configuration conf = new Configuration();
			String dictionary_name = conf.getDictionaryFile();
			Connection con = null;
			String url = "jdbc:mysql://localhost:3306/";
			String db = "cpmnew";
			String driver = "com.mysql.jdbc.Driver";

			try {
				Class.forName(driver);
				con = DriverManager.getConnection(url + db, "root", "");
			} catch (Exception e) {
				e.printStackTrace();
			}

			HashMap<String, Integer> map = new HashMap<String, Integer>();

			PreparedStatement statement;

			FileReader fr = new FileReader(dictionary_name);// reading from
			// dictionary
			BufferedReader fbr = new BufferedReader(fr);

			String str = fbr.readLine();
			int n = 0;
			String trigram = "";
			String finalToken;

			String temp;
			int len;
			char[] c;
			int count = 0;

			int trigramid = 1;
			int total = 0;
			String sql1;
			String sql2;

			while (str != null) {
				count = str.length() + 2;

				total = total + count;
				n++;

				// then only proceed
				temp = str.concat("$$");
				finalToken = "$$".concat(temp);// add $$ before and after word
				len = finalToken.length();

				c = finalToken.toCharArray();// each word to character array
				for (int i = 0; i < (len - 2); i++) {// create trigrams
					int tri = 0;
					char[] cn = { c[i], c[i + 1], c[i + 2] };
					trigram = new String(cn);
					if (map.containsKey(trigram)) {
						tri = map.get(trigram);

					} else {
						tri = trigramid++;
						map.put(trigram, trigramid);
						sql1 = "INSERT INTO fulltrigramset(full_id, fulltrigram) VALUES(?, ?)";
						statement = con.prepareStatement(sql1);

						statement.setInt(1, tri);
						statement.setString(2, trigram);
						statement.executeUpdate();
					}

					sql2 = "INSERT INTO fullbioset(set_id, full_id) VALUES(?, ?)";
					statement = con.prepareStatement(sql2);

					statement.setInt(1, n);
					statement.setInt(2, tri);
					statement.executeUpdate();
				}

				str = fbr.readLine();
			}

			double avg = total / n;
			int a = (int) Math.floor(avg);
			System.out.println(a);
		} catch (Exception e) {
			System.out.println("Error: " + e);
		}

	}

}
